package com.kaiyidiannao.activity.daydaycoupon;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.kaiyidiannao.adapter.CommonViewpagerAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.DaydayCouponBean;
import com.kaiyidiannao.model.req.model.GetDayDayCouponShow;
import com.kaiyidiannao.model.req.model.PostAddFavorites;
import com.kaiyidiannao.model.req.model.PostPraise;
import com.kaiyidiannao.model.req.model.PostShoppingCarAdd;
import com.kaiyidiannao.view.ActionBarView;
import com.kaiyidiannao.view.SpecLinelayout;

import java.util.*;

/**
 * Created by David on 14-4-2.
 * 天天惠详细类别
 */
public class DdcDetailActivity extends BaseActionBarActivity implements View.OnClickListener, Observer {
    //view相关
    private TextView details_money_integer; //商品价格整数部分
    private TextView details_money_decimal; //商品价格小数部分,要带个前面小数点
    private TextView product_name; //商品名称
    private ImageView collect; //商品收藏按钮
    private View priase; //点赞
    private TextView product_detail; //商品详细介绍
    private View purchase; //立即购买按钮
    private View addShopingCar; //加入购物车按钮
    private LinearLayout specLinearlayout;//商品规格Linearlayout
    private DaydayCouponBean bean;

    private int[] specsNum = {0, 0, 0};
    private boolean collectFlag, priaseFlag;
    private String itemid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.daydaycoupon_detail_activity);
        // 添加观察者
        DataCenter.getInstance().addObserver(this);
        findViews();
        //处理ActionBar
        findActionBar();

        itemid = getIntent().getStringExtra("itemid");
        Log.d("itemid...",itemid+"++");
        showProgressDialog();
        if (isLogin()) {
            new GetDayDayCouponShow(itemid, getUserid()).execute();
        } else {
            new GetDayDayCouponShow(itemid).execute();
        }
    }

//    private boolean isFirst = true;
//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        // TODO Auto-generated method stub
//        super.onWindowFocusChanged(hasFocus);
//        if(hasFocus && isFirst){
//           showPopWindow();
//            isFirst = false;
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //删除观察者
        DataCenter.daydayCouponBean = null;
        DataCenter.getInstance().deleteObserver(this);
    }

    private void findViews() {
        details_money_integer = (TextView) findViewById(R.id.daydaycoupon_details_money_integer);
        details_money_decimal = (TextView) findViewById(R.id.daydaycoupon_details_money_decimal);
        product_name = (TextView) findViewById(R.id.daydaycoupon_product_name);
        priase = findViewById(R.id.daydaycoupon_product_fav);
        collect = (ImageView) findViewById(R.id.daydaycoupon_product_favorite);
        product_detail = (TextView) findViewById(R.id.daydaycoupon_product_detail);
        purchase = findViewById(R.id.daydaycoupon_buy);
        addShopingCar = findViewById(R.id.daydaycoupon_add_shopping_car);
        specLinearlayout = (LinearLayout) findViewById(R.id.daydaycoupon_details_size_layout);

        //八张详情图片
        detailViewPager = (ViewPager) findViewById(R.id.detail_ViewPager);
    }

    /**
     * 初始化8张详情图片
     */
    private ViewPager detailViewPager;
    private CommonViewpagerAdapter commonViewpagerAdapter;
    private List<View> imageList = new ArrayList<View>();
    private List<String> imageUrlList = new ArrayList<String>();

    private void initViewPage() {
        commonViewpagerAdapter = new CommonViewpagerAdapter(DdcDetailActivity.this, imageList, detailViewPager, imageUrlList);

        for (int i = 0; i < imageUrlList.size(); i++) {
            final int position = i;
            ImageView imageView = (ImageView) getLayoutInflater().inflate(R.layout.common_viewpager_item, null);
            imageLoader.displayImage(imageUrlList.get(i), imageView, super.options, null);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DdcDetailActivity.super.startImagePagerActivity(position, bean.getPicture());
                }
            });
            imageList.add(imageView);
        }

        detailViewPager.setAdapter(commonViewpagerAdapter);
    }


    private void initViews(DaydayCouponBean bean) {
        try {
        this.bean = bean;
        if (bean.isIs_fav()) { // 已经收藏
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.shoucanged));
            collectFlag = true;
        } else {
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
            collectFlag = false;
        }
            String product_price = bean.getPrice(); //  decimal  integer
            String product_integer = product_price.substring(0, product_price.indexOf("."));
            String product_decimal = product_price.substring(product_price.indexOf("."));
            details_money_integer.setText(product_integer);
            details_money_decimal.setText(product_decimal);
            product_detail.setText(bean.getIntroduce());
            product_name.setText("" + bean.getTitle());

            if (bean.isIs_praise()) { // 已经点赞过了http://www.3tixa.com:8086/kaiyi/group/join.php
                priase.setBackgroundResource(R.drawable.list_collection_block);
                priaseFlag = true;
            } else {
                priase.setBackgroundResource(R.drawable.list_collection_empty);
                priaseFlag = false;
            }

            //八张详情图片
            imageUrlList = bean.getPicture2();
            initViewPage();


            priase.setOnClickListener(this);
            collect.setOnClickListener(this);
            purchase.setOnClickListener(this);
            addShopingCar.setOnClickListener(this);


            //动态添加规格信息
            //1:获取规格数据
            //2：动态添加规格
            specsNum[0] = 0;
            if (!TextUtils.isEmpty(bean.getV1())) {
                String n1 = bean.getN1();
                String[] v1 = bean.getV1().split(DataCenter.DIVIDED_SYMBOLS);
                addSpecs(1, n1, v1);

            } else {
                addSpecs(1, "", new String[]{});
            }

            specsNum[1] = 1;
            if (!TextUtils.isEmpty(bean.getV2())) {
                String n2 = bean.getN2();
                String[] v2 = bean.getV2().split(DataCenter.DIVIDED_SYMBOLS);
                addSpecs(2, n2, v2);
            } else {
                addSpecs(2, "", new String[]{});
            }

            specsNum[2] = 2;
            if (!TextUtils.isEmpty(bean.getV3())) {
                String n3 = bean.getN3();
                String[] v3 = bean.getV3().split(DataCenter.DIVIDED_SYMBOLS);
                addSpecs(3, n3, v3);
            } else {
                addSpecs(3, "", new String[]{});
            }


        } catch (Exception e) {

        }
    }

    /**
     * 显示重新加载页面
     */
    private void showReloadView() {
        findViewById(R.id.daydaycoupon_detail_scrollview).setVisibility(View.GONE);
        findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog();
                findViewById(R.id.daydaycoupon_detail_scrollview).setVisibility(View.INVISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.GONE);
                if (isLogin()) {
                    new GetDayDayCouponShow(itemid, getUserid()).execute();
                } else {
                    new GetDayDayCouponShow(itemid).execute();
                }
            }
        });
    }

    /**
     * 添加规格
     *
     * @param num    规格编号
     * @param key    规格名称
     * @param values 规格取值
     */
    private void addSpecs(int num, String key, String[] values) {
        LinearLayout fatherView = (LinearLayout) specLinearlayout.getChildAt(num - 1);
        if (values.length >= 1) {
            fatherView.setVisibility(View.VISIBLE);
        }
        ((TextView) fatherView.findViewById(R.id.daydaycoupon_spec_detail_name)).setText("" + key + "："); // 规格名称
        ((TextView) fatherView.findViewById(R.id.daydaycoupon_spec_detail_num)).setText("" + num); //规格编号
        SpecLinelayout specContext = (SpecLinelayout) fatherView.findViewById(R.id.daydaycoupon_spec_detail_content); //规格取值

        specContext.setData(key, values, true);
    }

    private boolean cheakCommit() {

        for (int k = 0; k < specsNum.length; ++k) {
            if (specsNum[k] != -1) {

                LinearLayout fatherView = (LinearLayout) specLinearlayout.getChildAt(k);
                SpecLinelayout specContext = (SpecLinelayout) fatherView.findViewById(R.id.daydaycoupon_spec_detail_content);

                int Visibility = fatherView.getVisibility();

                if (Visibility == View.VISIBLE) {
                    if (!specContext.checkSelected()) {
                        showToast("请选择:" + specContext.getSpecsName());
                        return false;
                    }
                }

            }
        }
        return true;
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        closeProgressDialog();

        if (flag == DataCenter.flag.GET_DAY_DAY_COUPON_SHOW_SUCCESS) {//获取详情信息成功
            closePopWindow();
            findViewById(R.id.daydaycoupon_detail_scrollview).setVisibility(View.VISIBLE);
            findViewById(R.id.daydaycoupon_detail_btns).setVisibility(View.VISIBLE);

            bean = DataCenter.daydayCouponBean;
            if (bean != null) {
                if (bean.getPicture() != null) {
                    if (bean.getPicture().length == 0) {
                        detailViewPager.setBackgroundResource(R.drawable.ic_default);
                    }
                }
            }
            initViews(bean);
        } else if (flag == DataCenter.flag.GET_DAY_DAY_COUPON_SHOW_FAILED) {
            bean = null;
            showReloadView();
        } else if (flag == DataCenter.flag.SHOPPING_CAR_ADD_SUCESS) {
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                showToast(DataCenter.msg, "恭喜，添加到购物车成功！");
            } else {
                showToast(DataCenter.msg);
            }
        }


        if (flag == DataCenter.flag.POST_PRAISE_SUCESS) { //点赞成功
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                if (priaseFlag) {//从当前的点赞状态变成没有点赞
                    priaseFlag = false;
                    //title = "取消点赞";
                    showToast(R.string.praise_cancle);
                    priase.setBackgroundResource(R.drawable.list_collection_empty);
                } else {
                    //title = "点赞成功";
                    showToast(R.string.praise_add);
                    priaseFlag = true;
                    priase.setBackgroundResource(R.drawable.list_collection_block);
                }
            } else {
                showToast(DataCenter.msg, "点赞出现错误");
            }
        }

        if (flag == DataCenter.flag.GetAddMESSAGEINFO_SUCCESS) {//收藏成功,关注成功\
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                if (collectFlag) {//从当前的关注状态变成没有关注
                    collectFlag = false;
                    showToast(R.string.collect_cancle);
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
                } else {
                    showToast(R.string.collect_add);
                    collectFlag = true;
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucanged));
                }
            } else {
                showToast(DataCenter.msg, "收藏出现错误");
            }
        }
    }

    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("商品详情");

        // 购物车图标
        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon2.setImageResource(R.drawable.daydaycoupon_shopping_car);
        actionBarView.button_right_icon2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (!HttpUtils.isConnected()) {
            showToast("离线模式，无法操作，请连接网络");
            return;
        }

        if (bean == null) {
            showToast("详情加载失败");
            return;
        }
        if (!isLogin()) {
            startLoginOrRegistered();
            return;
        }

        String userid = DataCenter.userLogin.get(0).getUserid();
        switch (v.getId()) {
            case R.id.daydaycoupon_buy: //立即购买
                if (cheakCommit()) {
                    // 1：加入购物车
                    reqeustShopingCarAdd();
                    // 2:读取购物车数据
                    DdcDetailActivity.this.startActivity(new Intent(DdcDetailActivity.this, DdcShoppingCarActivity.class));
                }
                break;
            case R.id.daydaycoupon_add_shopping_car: //加入购物车
                if (cheakCommit()) {
                    reqeustShopingCarAdd();
                }
                break;
            case R.id.daydaycoupon_product_favorite: //收藏，或者关注
                String action = "add";
                if (collectFlag) {
                    action = "delete";
                }
                showProgressDialog();
                new PostAddFavorites(DataCenter.CATID_daydaycoupon, userid, action, bean.getItemid(), bean.getTitle()).execute();
                break;
            case R.id.daydaycoupon_product_fav: //点赞
                String actions = "add";// 没有点赞
                if (priaseFlag) {
                    actions = "delete";
                }
                showProgressDialog();
                new PostPraise(DataCenter.CATID_daydaycoupon, getUserid(), bean.getItemid(), actions).execute();
                break;
            case R.id.actionbar_right_button_icon2: //购物车
                if (isLogin()) {
                    startActivity(new Intent(DdcDetailActivity.this, DdcShoppingCarActivity.class));
                } else {
                    startLoginOrRegistered();
                }
                break;
        }
    }

    private void reqeustShopingCarAdd() {

        if (isLogin()) {
            // 拼凑参数
            TreeMap<String, String> specsMap = new TreeMap<String, String>();
            int size = specLinearlayout.getChildCount();
            for (int k = 0; k < size; ++k) {
                LinearLayout fatherView = (LinearLayout) specLinearlayout.getChildAt(k);
                String specsValuesId = ((TextView) fatherView.findViewById(R.id.daydaycoupon_spec_detail_num)).getText().toString(); //规格编号,规格取值为1,2,3

                SpecLinelayout specContext = (SpecLinelayout) fatherView.findViewById(R.id.daydaycoupon_spec_detail_content);
                String specsSelecteValue = specContext.getSelectedIndex() + "";//规格取值编号

                specsMap.put(specsValuesId, specsSelecteValue);
            }
            String userid = DataCenter.userLogin.get(0).getUserid();
            showProgressDialog();
            new PostShoppingCarAdd(bean.getItemid(), userid, specsMap).execute();
        }
    }
}